package org.example.aienglishapp_login.controller.loginlog;

import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import org.example.aienglishapp_login.annotation.debounce.Debounce;
import org.example.aienglishapp_login.entity.loginlog.LoginLog;
import org.example.aienglishapp_login.service.loginlog.LoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author Asus
 */
@RestController
@RequestMapping("/api/loginlog")
public class LoginLogController {

    @Autowired
    private LoginLogService loginLogService;

    // Get all login logs
    @GetMapping("/all")
    public ResponseEntity<List<LoginLog>> getAllLoginLogs() {
        List<LoginLog> logs = loginLogService.getAllLoginLogs();
        if (logs.isEmpty()) {
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(logs);
    }

    // delete login log by id
    @DeleteMapping("/delete/{info_id}")
    @Debounce(interval = 500)
    public ResponseEntity<Void> deleteLoginLog(@PathVariable Long info_id) {
        loginLogService.deleteLoginLog(info_id);
        return ResponseEntity.noContent().build();
    }

    /**
     * 导出
     *
     * @param response 响应对象
     * @param loginLog 查询对象
     */
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response, LoginLog loginLog) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("登录日志", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 查询列表数据
        List<LoginLog> list = loginLogService.getAllLoginLogs();

        // 导出数据
        EasyExcel.write(response.getOutputStream(), LoginLog.class).sheet("登录日志").doWrite(list);
    }
}
